package com.yupi.usercenter.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.usercenter.contant.UserContant;
import com.yupi.usercenter.exception.UserCenterException;
import com.yupi.usercenter.exception.UserCenterExceptionEnum;
import com.yupi.usercenter.model.domain.User;
import com.yupi.usercenter.service.UserService;
import com.yupi.usercenter.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.yupi.usercenter.exception.UserCenterExceptionEnum.DEFAULT_ERROR_CODE;

/**
 * @author Administrator
 * @description 针对表【user(用户)】的数据库操作Service实现类
 * @createDate 2023-10-25 16:40:07
 */

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @return
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1、校验参数是否为空
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new UserCenterException(UserCenterExceptionEnum.PARAMS_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new UserCenterException(DEFAULT_ERROR_CODE, "用户长度不能小于4");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new UserCenterException(DEFAULT_ERROR_CODE, "密码长度不能小于8");
        }

        // 账户不能包含所有特殊字符的正则表达式
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";

        // matches方法验证正则表达式字符串是否匹配指定的正则表达式模式。如果匹配成功，则返回true；否则，返回false。
        // 放入规则
        Pattern compile = Pattern.compile(validPattern);
        // 校验目标字符串
        Matcher matcher = compile.matcher(userAccount);
        // 对字符串进行匹配，匹配到的字符串可以在任何位置
        boolean isMatched = matcher.find();

        if (isMatched) {
            throw new UserCenterException(DEFAULT_ERROR_CODE, "账号包含特殊字符串！");
        }

        // 密码和校验密码相同，不相同返回提示错误
        if (!userPassword.equals(checkPassword)) {
            throw new UserCenterException(DEFAULT_ERROR_CODE, "输入的密码不一致！");
        }

        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new UserCenterException(DEFAULT_ERROR_CODE, "已存在该用户！");
        }

        // 密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((UserContant.SALT + userPassword).getBytes());
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean saveResult = this.save(user);
        // 因为实体对象User是Long类型，当返回值null值时，会有报错
        if (!saveResult) {
            throw new UserCenterException(UserCenterExceptionEnum.PARAMS_ERROR);
        }

        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request      请求体
     * @return
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1、校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new UserCenterException(UserCenterExceptionEnum.PARAMS_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new UserCenterException(DEFAULT_ERROR_CODE, "用户长度不能小于4");
        }
        if (userPassword.length() < 8) {
            throw new UserCenterException(DEFAULT_ERROR_CODE, "密码长度不能小于8");
        }

        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";

        // matches方法验证正则表达式字符串是否匹配指定的正则表达式模式。如果匹配成功，则返回true；否则，返回false。
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new UserCenterException(DEFAULT_ERROR_CODE, "账号包含特殊字符串！");
        }

        // 2、加密
        String encryptPassword = DigestUtils.md5DigestAsHex((UserContant.SALT + userPassword).getBytes());

        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login faild, userAccount cannot match userPassword");
            throw new UserCenterException(DEFAULT_ERROR_CODE, "输入的用户不存在，或密码不正确");
        }

        // 3、用户脱敏
        User safetyUser = getSafetyUser(user);

        // 4、记录用户登录态
        request.getSession().setAttribute(UserContant.USER_LOGIN_STATE, safetyUser);
        return safetyUser;

    }

    @Override
    public List<User> searchUsers(String username) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userMapper.selectList(queryWrapper);

        // 返回脱敏的用户数据
        return userList.stream().map(user -> getSafetyUser(user)).collect(Collectors.toList());
    }

    @Override
    public int deleteUser(long id) {

        User oldUser = userMapper.selectById(id);
        if (oldUser == null) {
            throw new UserCenterException(DEFAULT_ERROR_CODE, "用户不存在！无法删除！");
        }

        int result = userMapper.deleteById(id);
        if (result == 0) {
            throw new UserCenterException(DEFAULT_ERROR_CODE, "删除失败！");
        }

        return result;
    }

    /**
     * 用户脱敏
     * @param originUser
     * @return
     */
    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        // 3、用户脱敏
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setCreateTime(originUser.getCreateTime());

        return safetyUser;
    }


}




